using _RobotInspection.DTO;
using _RobotInspection.Entities;
using _RobotInspection.Models;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using _RobotInspection.Interfaces;
using Microsoft.AspNetCore.SignalR.Protocol;
using RobotInspection.Interfaces;
using RobotInspection.Entities;

namespace _RobotInspection.Services
{
    /// <summary>
    /// 点检计划服务类
    /// </summary>
    public class InspectionPlanService : IInspectionPlanService
    {
        private readonly ISqlSugarClient _db;
        private readonly IInspectionRecordGeneratorService _recordGeneratorService;

        public InspectionPlanService(ISqlSugarClient db, IInspectionRecordGeneratorService recordGeneratorService)
        {
            _db = db;
            _recordGeneratorService = recordGeneratorService;
        }

        /// <summary>
        /// 获取所有设备及其点检项（用于创建计划时选择）
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult<ApiResponse<List<EquipmentWithItemsDto>>>> GetEquipmentWithItemsAsync()
        {
            try
            {
                var equipmentList = await _db.Queryable<equipment>()
                    .Where(e => e.status == 1)
                    .OrderBy(e => e.id)
                    .ToListAsync();

                var result = new List<EquipmentWithItemsDto>();

                foreach (var eq in equipmentList)
                {
                    var items = await _db.Queryable<inspection_items>()
                        .Where(i => i.equipment_id == eq.id && i.status == 1)
                        .OrderBy(i => i.sort_order)
                        .ToListAsync();

                    var equipmentDto = new EquipmentWithItemsDto
                    {
                        Id = eq.id,
                        EquipmentName = eq.equipment_name,
                        EquipmentCode = eq.equipment_code,
                        CompanyName = eq.company_name,
                        Crew = eq.unit,
                        InspectionItems = items.Select(i => new InspectionItemDetailDto
                        {
                            Id = i.id,
                            ItemName = i.item_name,
                            ItemDescription = i.item_description,
                            StandardValue = i.standard_value,
                            Unit = i.unit,
                            SortOrder = i.sort_order
                        }).ToList()
                    };

                    result.Add(equipmentDto);
                }

                return new OkObjectResult(ApiResponse<List<EquipmentWithItemsDto>>.Success(result));
            }
            catch (Exception ex)
            {
                return new OkObjectResult(ApiResponse<List<EquipmentWithItemsDto>>.Error($"获取设备点检项失败：{ex.Message}"));
            }
        }

        /// <summary>
        /// 创建点检计划
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ActionResult<ApiResponse<long>>> CreateInspectionPlanAsync(CreateInspectionPlanDto dto)
        {
            try
            {
                // 验证计划名称是否重复
                var existingPlan = await _db.Queryable<inspection_plans>()
                    .Where(p => p.plan_name == dto.PlanName)
                    .FirstAsync();

                if (existingPlan != null)
                {
                    return new OkObjectResult(ApiResponse<long>.Error("计划名称已存在"));
                }
                // 验证创建人ID是否有效
                if (dto.CreatedBy.HasValue)
                {
                    var creator = await _db.Queryable<users>()
                        .Where(u => u.id == dto.CreatedBy.Value && u.status == 1)
                        .FirstAsync();

                    if (creator == null)
                    {
                        return new OkObjectResult(ApiResponse<long>.Error($"创建人ID {dto.CreatedBy.Value} 不存在或已停用"));
                    }
                }

                // 收集所有需要指派的用户ID
                var finalAssignedUserIds = new List<long>();

                // 如果有指派用户ID，验证其有效性
                if (dto.AssignedUserIds != null && dto.AssignedUserIds.Any())
                {
                    foreach (var userId in dto.AssignedUserIds)
                    {
                        var user = await _db.Queryable<users>()
                            .Where(u => u.id == userId && u.status == 1)
                            .FirstAsync();

                        if (user == null)
                        {
                            return new OkObjectResult(ApiResponse<long>.Error($"指派用户ID {userId} 不存在或已停用"));
                        }
                    }
                    finalAssignedUserIds.AddRange(dto.AssignedUserIds);
                }
                else
                {
                    // 如果没有指派用户ID，从equipment_user_relations表查询设备绑定的用户
                    var equipmentIds = dto.PlanItems.Select(p => p.EquipmentId).Distinct().ToList();
                    var equipmentUserRelations = await _db.Queryable<equipment_user_relations>()
                        .Where(eur => equipmentIds.Contains(eur.equipment_id) && eur.is_active == 1)
                        .ToListAsync();

                    if (equipmentUserRelations.Any())
                    {
                        var userIds = equipmentUserRelations.Select(eur => eur.user_id).Distinct().ToList();

                        // 验证这些用户是否有效
                        foreach (var userId in userIds)
                        {
                            var user = await _db.Queryable<users>()
                                .Where(u => u.id == userId && u.status == 1)
                                .FirstAsync();

                            if (user != null)
                            {
                                finalAssignedUserIds.Add(userId);
                            }
                        }
                    }

                    // 检查是否有设备没有绑定用户
                    var equipmentWithoutUsers = new List<long>();
                    foreach (var equipmentId in equipmentIds)
                    {
                        var hasUser = equipmentUserRelations.Any(eur => eur.equipment_id == equipmentId);
                        if (!hasUser)
                        {
                            equipmentWithoutUsers.Add(equipmentId);
                        }
                    }

                    if (equipmentWithoutUsers.Any())
                    {
                        return new OkObjectResult(ApiResponse<long>.Error($"以下设备没有绑定用户，无法自动指派：{string.Join(", ", equipmentWithoutUsers)}"));
                    }

                    if (!finalAssignedUserIds.Any())
                    {
                        return new OkObjectResult(ApiResponse<long>.Error("没有找到有效的指派用户，请检查设备用户绑定关系"));
                    }
                }

                // 验证设备和点检项的有效性
                foreach (var planItem in dto.PlanItems)
                {
                    // 验证设备是否存在
                    var equipment = await _db.Queryable<equipment>()
                        .Where(e => e.id == planItem.EquipmentId && e.status == 1)
                        .FirstAsync();

                    if (equipment == null)
                    {
                        return new OkObjectResult(ApiResponse<long>.Error($"设备ID {planItem.EquipmentId} 不存在或已停用"));
                    }

                    foreach (var itemId in planItem.ItemIds)
                    {
                        var item = await _db.Queryable<inspection_items>()
                            .Where(i => i.id == itemId && i.equipment_id == planItem.EquipmentId && i.status == 1)
                            .FirstAsync();

                        if (item == null)
                        {
                            return new OkObjectResult(ApiResponse<long>.Error($"点检项ID {itemId} 不存在或不属于设备 {planItem.EquipmentId}"));
                        }
                    }
                }

                // 开始事务
                var result = await _db.Ado.UseTranAsync(async () =>
                {
                    // 创建计划主记录
                    var plan = new inspection_plans
                    {
                        plan_name = dto.PlanName,
                        unit = dto.Unit,
                        plan_type = dto.PlanType,
                        frequency_value = dto.FrequencyValue,
                        start_date = dto.StartDate,
                        end_date = dto.EndDate,
                        is_holiday = dto.IsHoliday,
                        is_active = 1,
                        created_by = dto.CreatedBy,
                        created_at = DateTime.Now,
                        updated_at = DateTime.Now
                    };

                    var planId = await _db.Insertable(plan).ExecuteReturnIdentityAsync();

                    // 创建计划明细记录
                    var planItems = new List<inspection_plan_items>();
                    foreach (var planItem in dto.PlanItems)
                    {
                        foreach (var itemId in planItem.ItemIds)
                        {
                            planItems.Add(new inspection_plan_items
                            {
                                plan_id = planId,
                                equipment_id = planItem.EquipmentId,
                                item_id = itemId,
                                created_at = DateTime.Now
                            });
                        }
                    }

                    if (planItems.Any())
                    {
                        await _db.Insertable(planItems).ExecuteCommandAsync();
                    }

                    // 创建计划用户关联记录
                    if (finalAssignedUserIds != null && finalAssignedUserIds.Any())
                    {
                        var planUserRelations = finalAssignedUserIds.Select(userId => new plan_user_relations
                        {
                            plan_id = planId,
                            user_id = userId,
                            created_at = DateTime.Now
                        }).ToList();

                        await _db.Insertable(planUserRelations).ExecuteCommandAsync();
                    }

                    return planId;
                });
                if (!result.IsSuccess)
                {
                    return new OkObjectResult(ApiResponse<object>.Error($"点检计划创建失败：{result.ErrorMessage}"));
                }

                // 如果IsNow为true，立即生成点检记录
                if (dto.IsNow == 1)
                {
                    try
                    {
                        var generateResult = await _recordGeneratorService.GenerateInspectionRecordsForPlan(result.Data, DateTime.Today);
                        // 注意：即使生成记录失败，计划创建仍然成功，只是在返回消息中提示
                        
                        // 正确地从ActionResult中提取ApiResponse对象
                        if (generateResult.Result is OkObjectResult okResult && okResult.Value is ApiResponse<object> apiResponse)
                        {
                            if (apiResponse.Code == 200)
                            {
                                return new OkObjectResult(ApiResponse<long>.Success(result.Data, "点检计划创建成功，并已自动生成今日点检记录"));
                            }
                            else
                            {
                                return new OkObjectResult(ApiResponse<long>.Success(result.Data, $"点检计划创建成功，但生成点检记录失败：{apiResponse.Message}"));
                            }
                        }
                        else
                        {
                            return new OkObjectResult(ApiResponse<long>.Success(result.Data, "点检计划创建成功，但生成点检记录时返回格式异常"));
                        }
                    }
                    catch (Exception ex)
                    {
                        return new OkObjectResult(ApiResponse<long>.Success(result.Data, $"点检计划创建成功，但生成点检记录时发生异常：{ex.Message}"));
                    }
                }

                return new OkObjectResult(ApiResponse<long>.Success(result.Data, "点检计划创建成功"));
            }
            catch (Exception ex)
            {
                return new OkObjectResult(ApiResponse<long>.Error($"创建点检计划失败：{ex.Message}"));
            }
        }

        /// <summary>
        /// 获取点检计划列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ActionResult<ApiResponse<PagedResult<InspectionPlanResponseDto>>>> GetInspectionPlansAsync(InspectionPlanQueryDto query)
        {
            try
            {
                var queryable = _db.Queryable<inspection_plans>()
                    .LeftJoin<users>((p, u) => p.created_by == u.id)
                    .WhereIF(!string.IsNullOrWhiteSpace(query.PlanName), (p, u) => p.plan_name.Contains(query.PlanName))
                    .WhereIF(query.PlanType.HasValue, (p, u) => p.plan_type == query.PlanType.Value)
                    .WhereIF(query.IsActive.HasValue, (p, u) => p.is_active == query.IsActive.Value)
                    .WhereIF(query.CreatedBy.HasValue, (p, u) => p.created_by == query.CreatedBy.Value)
                    .OrderBy((p, u) => p.created_at, OrderByType.Desc);

                var totalCount = await queryable.CountAsync();

                var plans = await queryable
                    .Select((p, u) => new InspectionPlanResponseDto
                    {
                        Id = p.id,
                        PlanName = p.plan_name,
                        PlanType = p.plan_type,
                        PlanTypeName = GetPlanTypeName(p.plan_type),
                        FrequencyValue = p.frequency_value,
                        StartDate = p.start_date,
                        EndDate = p.end_date,
                        IsActive = p.is_active,
                        CreatedBy = p.created_by,
                        CreatedByName = u.real_name,
                        CreatedAt = p.created_at,
                        UpdatedAt = p.updated_at
                    })
                    .ToPageListAsync(query.PageIndex, query.PageSize);

                // 获取每个计划的详细项目信息
                foreach (var plan in plans)
                {
                    plan.PlanItems = await GetPlanItemsAsync(plan.Id);
                }

                var result = new PagedResult<InspectionPlanResponseDto>
                {
                    Items = plans,
                    TotalCount = totalCount,
                    PageIndex = query.PageIndex,
                    PageSize = query.PageSize,
                    TotalPages = (int)Math.Ceiling((double)totalCount / query.PageSize)
                };

                return new OkObjectResult(ApiResponse<PagedResult<InspectionPlanResponseDto>>.Success(result, "", totalCount));
            }
            catch (Exception ex)
            {
                return new OkObjectResult(ApiResponse<PagedResult<InspectionPlanResponseDto>>.Error($"获取点检计划列表失败：{ex.Message}"));
            }
        }

        /// <summary>
        /// 根据计划ID获取计划详情
        /// </summary>
        /// <param name="planId"></param>
        /// <returns></returns>
        public async Task<ActionResult<ApiResponse<InspectionPlanResponseDto>>> GetInspectionPlanByIdAsync(long planId)
        {
            try
            {
                // 第一步：数据库查询（不要在Select里调用C#函数）
                var planData = await _db.Queryable<inspection_plans>()
                    .LeftJoin<users>((p, u) => p.created_by == u.id)
                    .Where((p, u) => p.id == planId)
                    .Select((p, u) => new
                    {
                        Id = p.id,
                        PlanName = p.plan_name,
                        PlanType = p.plan_type,
                        FrequencyValue = p.frequency_value,
                        StartDate = p.start_date,
                        EndDate = p.end_date,
                        IsActive = p.is_active,
                        CreatedBy = p.created_by,
                        CreatedByName = u.real_name,
                        CreatedAt = p.created_at,
                        UpdatedAt = p.updated_at
                    })
                    .FirstAsync();

                if (planData == null)
                {
                    return new OkObjectResult(ApiResponse<InspectionPlanResponseDto>.Error("点检计划不存在"));
                }


                var plan = new InspectionPlanResponseDto
                {
                    Id = planData.Id,
                    PlanName = planData.PlanName,
                    PlanType = planData.PlanType,
                    PlanTypeName = GetPlanTypeName(planData.PlanType),
                    FrequencyValue = planData.FrequencyValue,
                    StartDate = planData.StartDate,
                    EndDate = planData.EndDate,
                    IsActive = planData.IsActive,
                    CreatedBy = planData.CreatedBy,
                    CreatedByName = planData.CreatedByName,
                    CreatedAt = planData.CreatedAt,
                    UpdatedAt = planData.UpdatedAt,
                    PlanItems = await GetPlanItemsAsync(planId)
                };

                return new OkObjectResult(ApiResponse<InspectionPlanResponseDto>.Success(plan));
            }
            catch (Exception ex)
            {
                return new OkObjectResult(ApiResponse<InspectionPlanResponseDto>.Error($"获取点检计划详情失败：{ex.Message}"));
            }
        }

        /// <summary>
        /// 启用/禁用点检计划
        /// </summary>
        /// <param name="planId"></param>
        /// <param name="isActive"></param>
        /// <returns></returns>
        public async Task<ActionResult<ApiResponse<bool>>> UpdatePlanStatusAsync(long planId, byte isActive)
        {
            try
            {
                var plan = await _db.Queryable<inspection_plans>()
                    .Where(p => p.id == planId)
                    .FirstAsync();

                if (plan == null)
                {
                    return new OkObjectResult(ApiResponse<bool>.Error("点检计划不存在"));
                }

                await _db.Updateable<inspection_plans>()
                    .SetColumns(p => new inspection_plans
                    {
                        is_active = isActive,
                        updated_at = DateTime.Now
                    })
                    .Where(p => p.id == planId)
                    .ExecuteCommandAsync();

                return new OkObjectResult(ApiResponse<bool>.Success(true, $"计划已{(isActive == 1 ? "启用" : "禁用")}"));
            }
            catch (Exception ex)
            {
                return new OkObjectResult(ApiResponse<bool>.Error($"更新计划状态失败：{ex.Message}"));
            }
        }

        /// <summary>
        /// 获取计划项目详情
        /// </summary>
        /// <param name="planId"></param>
        /// <returns></returns>
        private async Task<List<PlanItemDetailDto>> GetPlanItemsAsync(long planId)
        {
            var planItems = await _db.Queryable<inspection_plan_items>()
                .LeftJoin<equipment>((pi, e) => pi.equipment_id == e.id)
                .LeftJoin<inspection_items>((pi, e, i) => pi.item_id == i.id && i.equipment_id == pi.equipment_id)
                .Where((pi, e, i) => pi.plan_id == planId)
                .Select((pi, e, i) => new
                {
                    EquipmentId = pi.equipment_id,
                    EquipmentName = e.equipment_name,
                    EquipmentCode = e.equipment_code,
                    ItemId = i.id,
                    ItemName = i.item_name,
                    ItemDescription = i.item_description,
                    StandardValue = i.standard_value,
                    Unit = i.unit,
                    SortOrder = i.sort_order
                })
                .ToListAsync();

            var result = planItems
                .GroupBy(x => new { x.EquipmentId, x.EquipmentName, x.EquipmentCode })
                .Select(g => new PlanItemDetailDto
                {
                    EquipmentId = g.Key.EquipmentId,
                    EquipmentName = g.Key.EquipmentName,
                    EquipmentCode = g.Key.EquipmentCode,
                    Items = g.Select(x => new InspectionItemDetailDto
                    {
                        Id = x.ItemId,
                        ItemName = x.ItemName,
                        ItemDescription = x.ItemDescription,
                        StandardValue = x.StandardValue,
                        Unit = x.Unit,
                        SortOrder = x.SortOrder
                    }).ToList()
                })
                .ToList();

            return result;
        }

        /// <summary>
        /// 获取计划类型名称
        /// </summary>
        /// <param name="planType"></param>
        /// <returns></returns>
        private string GetPlanTypeName(byte planType)
        {
            return planType switch
            {
                1 => "日点检",
                2 => "周点检",
                3 => "月点检",
                4 => "一次性点检",
                _ => "未知类型"
            };
        }


        /// <summary>
        /// 获取所有公司及其机组（用于创建计划时选择）
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult<ApiResponse<List<EquipmentHierarchyDto>>>> GetCompanyWithCrewAsync()
        {
            try
            {
                var equipments = await _db.Queryable<equipment>()
                   .Where(e => e.status == 1)
                   .Select(e => new { e.id, e.company_name, e.unit, e.equipment_name })
                   .ToListAsync();

                var result = equipments
                    .GroupBy(e => e.company_name)
                    .Select(g => new EquipmentHierarchyDto
                    {
                        CompanyName = g.Key,
                        Unit = g.GroupBy(x => x.unit)
                                 .Select(cg => new CrewDto
                                 {
                                     UnitName = cg.Key,
                                     Equipments = cg.Select(x => new EquipmentDto
                                     {
                                         Id = x.id,
                                         EquipmentName = x.equipment_name
                                     }).ToList()
                                 }).ToList()
                    })
                    .ToList();


                return new OkObjectResult(ApiResponse<List<EquipmentHierarchyDto>>.Success(result));
            }
            catch (Exception ex)
            {
                return new OkObjectResult(ApiResponse<object>.Error($"获取公司及机组失败：{ex.Message}"));
            }
        }

        /// <summary>
        /// 根据id获取点检项目
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult<ApiResponse<object>>> GetInspectionItems(long id)
        {
            try
            {
                var InspectionItems = await _db.Queryable<inspection_items>()
                    .Where(e => e.equipment_id == id && e.status == 1)
                    .Select(e => new { e.id, e.item_name, e.item_description })
                    .ToListAsync();

                return new OkObjectResult(ApiResponse<object>.Success(InspectionItems));
            }
            catch (Exception ex)
            {
                return new OkObjectResult(ApiResponse<object>.Error($"获取公司及机组失败：{ex.Message}"));
            }
        }

        /// <summary>
        /// 根据机组查询点检计划列表
        /// </summary>
        /// <param name="unit">机组名称</param>
        /// <param name="planType">点检周期类型（可选）</param>
        /// <returns></returns>
        public async Task<ActionResult<ApiResponse<List<InspectionPlanByUnitDto>>>> GetInspectionPlansByUnitAsync(string unit, byte? planType = null)
        {

            throw new NotImplementedException();
            try
            {

                if (string.IsNullOrWhiteSpace(unit))
                {
                    return new OkObjectResult(ApiResponse<List<InspectionPlanByUnitDto>>.Error("机组名称不能为空"));
                }

                // 查询指定机组的点检计划，支持按点检周期过滤
                var queryable = _db.Queryable<inspection_plans>()
                    .Where(p => p.unit == unit && p.is_active == 1);

                // 如果指定了点检周期类型，则添加过滤条件
                if (planType.HasValue)
                {
                    queryable = queryable.Where(p => p.plan_type == planType.Value);
                }

                // 获取总记录数
                var totalCount = await queryable.CountAsync();



                // return new OkObjectResult(ApiResponse<List<InspectionPlanByUnitDto>>.Success(result, message));
            }
            catch (Exception ex)
            {
                return new OkObjectResult(ApiResponse<List<InspectionPlanByUnitDto>>.Error($"查询失败：{ex.Message}"));
            }
        }

        /// <summary>
        /// 分页查询点检计划
        /// </summary>
        /// <param name="queryDto">查询条件</param>
        /// <returns></returns>
        public async Task<ActionResult<ApiResponse<InspectionPlanPagedResultDto>>> GetInspectionPlansPagedAsync(InspectionPlanPagedQueryDto queryDto)
        {
            try
            {
                // 验证参数
                if (queryDto.PageIndex < 1) queryDto.PageIndex = 1;
                if (queryDto.PageSize < 1) queryDto.PageSize = 20;
                if (queryDto.PageSize > 100) queryDto.PageSize = 100; // 限制最大页大小

                // 根据查询条件选择不同的查询方法
                if (!string.IsNullOrWhiteSpace(queryDto.Unit))
                {
                    return await GetInspectionPlansByUnitPagedAsync(queryDto);
                }
                else if (queryDto.EquipmentId.HasValue)
                {
                    return await GetInspectionPlansByEquipmentIdPagedAsync(queryDto);
                }
                else
                {
                    return new OkObjectResult(ApiResponse<InspectionPlanPagedResultDto>.Error("请提供机组名称或设备ID作为查询条件"));
                }
            }
            catch (Exception ex)
            {
                return new OkObjectResult(ApiResponse<InspectionPlanPagedResultDto>.Error($"查询失败：{ex.Message}"));
            }
        }

        /// <summary>
        /// 按机组分页查询点检计划详情
        /// </summary>
        /// <param name="queryDto">查询条件</param>
        /// <returns></returns>
        private async Task<ActionResult<ApiResponse<InspectionPlanPagedResultDto>>> GetInspectionPlansByUnitPagedAsync(InspectionPlanPagedQueryDto queryDto)
        {
            try
            {
                // 构建查询条件
                var queryable = _db.Queryable<inspection_plans>()
                    .Where(p => p.unit == queryDto.Unit);

                // 添加其他过滤条件
                if (queryDto.PlanType.HasValue)
                {
                    queryable = queryable.Where(p => p.plan_type == queryDto.PlanType.Value);
                }

                if (!string.IsNullOrWhiteSpace(queryDto.PlanName))
                {
                    queryable = queryable.Where(p => p.plan_name.Contains(queryDto.PlanName));
                }

                if (queryDto.IsActive.HasValue)
                {
                    queryable = queryable.Where(p => p.is_active == queryDto.IsActive.Value);
                }
                else
                {
                    // 默认只查询启用的计划
                    queryable = queryable.Where(p => p.is_active == 1);
                }

                // 获取总记录数
                var totalCount = await queryable.CountAsync();

                // 使用SqlSugar的分页方法
                var plans = await queryable
                    .OrderBy(p => p.created_at, OrderByType.Desc)
                    .ToPageListAsync(queryDto.PageIndex, queryDto.PageSize);

                // 获取所有计划ID
                var planIds = plans.Select(p => p.id).ToList();

                // 一次性查询所有计划的点检项数量
                var planItemCounts = await _db.Queryable<inspection_plan_items>()
                    .Where(pi => planIds.Contains(pi.plan_id))
                    .GroupBy(pi => pi.plan_id)
                    .Select(g => new { PlanId = g.plan_id, ItemCount = SqlFunc.AggregateCount(g.id) })
                    .ToListAsync();

                // 创建计划ID到点检项数量的映射
                var planItemCountMap = planItemCounts.ToDictionary(p => p.PlanId, p => p.ItemCount);

                // 构建结果
                var items = new List<InspectionPlanByUnitDto>();

                foreach (var plan in plans)
                {
                    // 从映射中获取点检项数量，如果没有则为0
                    var itemCount = planItemCountMap.ContainsKey(plan.id) ? planItemCountMap[plan.id] : 0;

                    var planDto = new InspectionPlanByUnitDto
                    {
                        Id = plan.id,
                        PlanName = plan.plan_name,
                        Unit = plan.unit,
                        PlanType = plan.plan_type,
                        PlanTypeName = GetPlanTypeName(plan.plan_type),
                        FrequencyValue = plan.frequency_value,
                        StartDate = plan.start_date,
                        EndDate = plan.end_date,
                        IsHoliday = plan.is_holiday,
                        IsHolidayName = plan.is_holiday == 1 ? "跳过节假日" : "不跳过节假日",
                        ItemCount = itemCount,
                        IsActive = plan.is_active ?? 1,
                        CreatedAt = plan.created_at
                    };

                    items.Add(planDto);
                }

                // 构建结果，但不包含分页参数
                var result = new InspectionPlanPagedResultDto
                {
                    Items = items,
                    TotalCount = totalCount,
                    TotalPages = 0,
                    CurrentPage = 0,
                    PageSize = 0,
                    HasPreviousPage = false,
                    HasNextPage = false
                };

                var message = $"查询到机组 '{queryDto.Unit}' 的点检计划总数：{totalCount}";
                return new OkObjectResult(ApiResponse<InspectionPlanPagedResultDto>.Success(result, message, totalCount));
            }
            catch (Exception ex)
            {
                return new OkObjectResult(ApiResponse<InspectionPlanPagedResultDto>.Error($"查询机组点检计划失败：{ex.Message}"));
            }
        }

        /// <summary>
        /// 按设备ID分页查询点检计划
        /// </summary>
        /// <param name="queryDto">查询条件</param>
        /// <returns></returns>
        private async Task<ActionResult<ApiResponse<InspectionPlanPagedResultDto>>> GetInspectionPlansByEquipmentIdPagedAsync(InspectionPlanPagedQueryDto queryDto)
        {
            try
            {
                // 获取设备关联的所有计划ID，而不是只获取第一个
                var planIds = await _db.Queryable<inspection_plan_items>()
                    .Where(p => p.equipment_id == queryDto.EquipmentId.Value)
                    .Select(p => p.plan_id)
                    .Distinct()
                    .ToListAsync();

                if (planIds == null || !planIds.Any())
                {
                    return new OkObjectResult(ApiResponse<InspectionPlanPagedResultDto>.Error("未找到对应的点检计划"));
                }

                // 构建查询条件
                var queryable = _db.Queryable<inspection_plans>()
                    .Where(p => planIds.Contains(p.id));

                // 添加其他过滤条件
                if (queryDto.PlanType.HasValue)
                {
                    queryable = queryable.Where(p => p.plan_type == queryDto.PlanType.Value);
                }

                if (!string.IsNullOrWhiteSpace(queryDto.PlanName))
                {
                    queryable = queryable.Where(p => p.plan_name.Contains(queryDto.PlanName));
                }

                if (queryDto.IsActive.HasValue)
                {
                    queryable = queryable.Where(p => p.is_active == queryDto.IsActive.Value);
                }
                else
                {
                    // 默认只查询启用的计划
                    queryable = queryable.Where(p => p.is_active == 1);
                }

                // 获取总记录数
                var totalCount = await queryable.CountAsync();

                // 使用SqlSugar的分页方法
                var plans = await queryable
                    .OrderBy(p => p.created_at, OrderByType.Desc)
                    .ToPageListAsync(queryDto.PageIndex, queryDto.PageSize);

                // 获取所有计划ID
                var resultPlanIds = plans.Select(p => p.id).ToList();

                // 一次性查询所有计划的点检项数量
                var planItemCounts = await _db.Queryable<inspection_plan_items>()
                    .Where(pi => resultPlanIds.Contains(pi.plan_id))
                    .GroupBy(pi => pi.plan_id)
                    .Select(g => new { PlanId = g.plan_id, ItemCount = SqlFunc.AggregateCount(g.id) })
                    .ToListAsync();

                // 创建计划ID到点检项数量的映射
                var planItemCountMap = planItemCounts.ToDictionary(p => p.PlanId, p => p.ItemCount);

                // 构建结果
                var items = new List<InspectionPlanByUnitDto>();

                foreach (var plan in plans)
                {
                    // 从映射中获取点检项数量，如果没有则为0
                    var itemCount = planItemCountMap.ContainsKey(plan.id) ? planItemCountMap[plan.id] : 0;

                    var planDto = new InspectionPlanByUnitDto
                    {
                        Id = plan.id,
                        PlanName = plan.plan_name,
                        Unit = plan.unit,
                        PlanType = plan.plan_type,
                        PlanTypeName = GetPlanTypeName(plan.plan_type),
                        FrequencyValue = plan.frequency_value,
                        StartDate = plan.start_date,
                        EndDate = plan.end_date,
                        IsHoliday = plan.is_holiday,
                        IsHolidayName = plan.is_holiday == 1 ? "跳过节假日" : "不跳过节假日",
                        ItemCount = itemCount,
                        IsActive = plan.is_active ?? 1,
                        CreatedAt = plan.created_at
                    };

                    items.Add(planDto);
                }

                // 构建结果，但不包含分页参数
                var result = new InspectionPlanPagedResultDto
                {
                    Items = items,
                    TotalCount = totalCount,
                    TotalPages = 0,
                    CurrentPage = 0,
                    PageSize = 0,
                    HasPreviousPage = false,
                    HasNextPage = false
                };

                var equipmentName = await _db.Queryable<equipment>()
                    .Where(e => e.id == queryDto.EquipmentId.Value)
                    .Select(e => e.equipment_name)
                    .FirstAsync();

                var message = $"查询到设备 '{equipmentName}' 的点检计划总数：{totalCount}";
                return new OkObjectResult(ApiResponse<InspectionPlanPagedResultDto>.Success(result, message, totalCount));
            }
            catch (Exception ex)
            {
                return new OkObjectResult(ApiResponse<InspectionPlanPagedResultDto>.Error($"查询设备点检计划失败：{ex.Message}"));
            }
        }
    }

    /// <summary>
    /// 分页结果类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class PagedResult<T>
    {
        /// <summary>
        /// 数据列表
        /// </summary>
        public List<T> Items { get; set; } = new List<T>();

        /// <summary>
        /// 总记录数
        /// </summary>
        public int TotalCount { get; set; }

        /// <summary>
        /// 当前页码
        /// </summary>
        public int PageIndex { get; set; }

        /// <summary>
        /// 页大小
        /// </summary>
        public int PageSize { get; set; }

        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPages { get; set; }

        /// <summary>
        /// 是否有上一页
        /// </summary>
        public bool HasPreviousPage => PageIndex > 1;

        /// <summary>
        /// 是否有下一页
        /// </summary>
        public bool HasNextPage => PageIndex < TotalPages;
    }
}